package cn.sz.dzy.provider.controller;

import cn.hutool.json.JSONUtil;
import cn.sz.dzy.common.pojo.*;
import cn.sz.dzy.provider.service.ISessionService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @program: gta1400
 * @description: 注册注销接口
 * @author: DingZhenYun
 * @create: 2021-12-07 15:31
 **/
@Api(tags = "VIIDSystem")
@RestController
@RequestMapping("/VIID/System")
@Slf4j
public class SessionController {

    @Autowired
    private ISessionService sessionService;

    @Value(value = "${server.username}")
    private String username;

    @Value(value = "${server.password}")
    private String password;

    @PostMapping("/Register")
    public ResponseEntity<String> Register(HttpEntity<String> httpEntity) {
        String body = httpEntity.getBody();
        HttpHeaders headers = httpEntity.getHeaders();
        log.info("body：{}", body);
        log.info("headers：{}", headers);
        RegisterRequestObject registerRequestObject = JSONUtil.toBean(body, RegisterRequestObject.class);
        log.info("registerObject：{}", registerRequestObject.toString());
        List<String> authorizationList = headers.get("Authorization");
        if (authorizationList != null && authorizationList.size() != 0) {
            String authorization = headers.get("Authorization").get(0);
            if (authorization != null && authorization.length() != 0) {
                log.info("authorization：{}", authorization);
                //第二次请求
                String[] children = authorization.split(",");
                // Digest realm="myrealm",qop="auth",nonce="dmktZGlnZXN0OjQzNTQyNzI3Nzg="
                String realm = null, qop = null, nonce = null, opaque = null, method = "POST";
                String nc = "";
                String cnonce = "";
                String response = "";
                String uri = "";
                for (int i = 0; i < children.length; i++) {
                    String item = children[i];
                    String[] itemEntry = item.split("=");
                    if (itemEntry[0].equals("nc")) {
                        nc = itemEntry[1].replaceAll("\"", "");
                    } else if (itemEntry[0].equals("cnonce")) {
                        cnonce = itemEntry[1].replaceAll("\"", "");
                    } else if (itemEntry[0].equals("response")) {
                        response = itemEntry[1].replaceAll("\"", "");
                    } else if (itemEntry[0].equals("uri")) {
                        uri = itemEntry[1].replaceAll("\"", "");
                    }
                }
                log.info("nc：{}", nc);
                log.info("cnonce：{}", cnonce);
                log.info("response：{}", response);
                EncryptionPwVO encryptionPwVO = new EncryptionPwVO();
                encryptionPwVO.setUsername(username);
                encryptionPwVO.setPassword(password);
                encryptionPwVO.setCnonce(cnonce);
                encryptionPwVO.setNc(nc);
                encryptionPwVO.setResponse(response);
                encryptionPwVO.setUri(uri);
                ResponseEntity<String> responseEntity = sessionService.secondRegister(encryptionPwVO, registerRequestObject);
                log.info("第二次responseEntity：{}", responseEntity.toString());
                return responseEntity;
            }

        }
        ResponseEntity<String> responseEntity = sessionService.firstRegister(registerRequestObject);
        log.info("c--responseEntity：{}", responseEntity.toString());
        return responseEntity;
    }


    @PostMapping("/UnRegister")
    public ResponseEntity<String> UnRegister(HttpEntity<String> httpEntity) {
        String body = httpEntity.getBody();
        HttpHeaders headers = httpEntity.getHeaders();
        log.info("body：{}", body);
        log.info("headers：{}", headers);
        UnRegisterRequestObject unRegisterRequestObject = JSONUtil.toBean(body, UnRegisterRequestObject.class);
        log.info("unregisterRequestObject：{}", unRegisterRequestObject.toString());
        List<String> authorizationList = headers.get("Authorization");
        if (authorizationList != null && authorizationList.size() != 0) {
            String authorization = headers.get("Authorization").get(0);
            if (authorization != null && authorization.length() != 0) {
                log.info("authorization：{}", authorization);
                //第二次请求
                String[] children = authorization.split(",");
                // Digest realm="myrealm",qop="auth",nonce="dmktZGlnZXN0OjQzNTQyNzI3Nzg="
                String realm = null, qop = null, nonce = null, opaque = null, method = "POST";
                String nc = "";
                String cnonce = "";
                String response = "";
                String uri = "";
                for (int i = 0; i < children.length; i++) {
                    String item = children[i];
                    String[] itemEntry = item.split("=");
                    if (itemEntry[0].equals("nc")) {
                        nc = itemEntry[1].replaceAll("\"", "");
                    } else if (itemEntry[0].equals("cnonce")) {
                        cnonce = itemEntry[1].replaceAll("\"", "");
                    } else if (itemEntry[0].equals("response")) {
                        response = itemEntry[1].replaceAll("\"", "");
                    } else if (itemEntry[0].equals("uri")) {
                        uri = itemEntry[1].replaceAll("\"", "");
                    }
                }
                log.info("nc：{}", nc);
                log.info("cnonce：{}", cnonce);
                log.info("response：{}", response);
                EncryptionPwVO encryptionPwVO = new EncryptionPwVO();
                encryptionPwVO.setUsername(username);
                encryptionPwVO.setPassword(password);
                encryptionPwVO.setCnonce(cnonce);
                encryptionPwVO.setNc(nc);
                encryptionPwVO.setResponse(response);
                encryptionPwVO.setUri(uri);
                ResponseEntity<String> responseEntity = sessionService.secondunregister(encryptionPwVO, unRegisterRequestObject);
                log.info("第二次responseEntity：{}", responseEntity.toString());
                return responseEntity;
            }

        }
        ResponseEntity<String> responseEntity = sessionService.firstunregister(unRegisterRequestObject);
        log.info("c--responseEntity：{}", responseEntity.toString());
        return responseEntity;
    }

    @PostMapping("/Keepalive")
    public ResponseEntity<String> Keepalive(HttpEntity<String> httpEntity) {
        String body = httpEntity.getBody();
        HttpHeaders headers = httpEntity.getHeaders();
        log.info("body：{}", body);
        log.info("headers：{}", headers);
        KeepaliveRequestObject keepaliveRequestObject = JSONUtil.toBean(body, KeepaliveRequestObject.class);
        log.info("unregisterRequestObject：{}", keepaliveRequestObject.toString());
        ResponseEntity<String> responseEntity = sessionService.keepalive(keepaliveRequestObject);
        log.info("c--responseEntity：{}", responseEntity.toString());
        return responseEntity;
    }

    @GetMapping("/Time")
    public ResponseEntity<String> time(HttpEntity<String> httpEntity) {
        HttpHeaders headers = httpEntity.getHeaders();
        log.info("time-headers：{}", headers);
        List<String> strings = headers.get("user-identify");
        log.info("time-strings：{}", strings);
        if (strings.size() != 0 && strings != null) {
            String useridentify = strings.get(0);//设备id
            log.info("time-useridentify：{}", useridentify);
            SystemTimeObject systemTimeObject = new SystemTimeObject();
            SystemTimeObject.SystemTime systemTime = systemTimeObject.new SystemTime();
            systemTime.setVIIDServerID(useridentify);
            systemTimeObject.setSystemTime(systemTime);
            log.info("time-systemTimeObject：{}", systemTimeObject.toString());
            ResponseEntity<String> responseEntity = sessionService.time(systemTimeObject);
            log.info("time-c--systemTimeObject：{}", responseEntity.toString());
            return responseEntity;
        }
        return null;
    }
}
